import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn import metrics
from xgboost import XGBRegressor

try:
    # 读取指定路径的 CSV 文件
    df = pd.read_csv(r"/Users/guopeiran/Code/VSCode/Something/something/housing.csv")
    df.info()
    df.describe()

    # 假设最后一列为目标变量
    X = df.iloc[:, :-1]
    y = df.iloc[:, -1]

    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.3, random_state=42)

    # 创建并训练带有预定义参数的 XGBRegressor 模型
    model = XGBRegressor(n_estimators=150, max_depth=4,
                        subsample=0.8, colsample_bytree=0.9,
                        learning_rate=0.2)
    model.fit(X_train, y_train)

    # 进行预测
    y_pred = model.predict(X_test)

    # 评估模型
    print("MAE:", metrics.mean_absolute_error(y_test, y_pred))
    mse = metrics.mean_squared_error(y_test, y_pred)
    rmse = np.sqrt(mse)
    print("RMSE:", rmse)
    print("R_squared:", metrics.r2_score(y_test, y_pred))

except FileNotFoundError:
    print("未找到指定的 CSV 文件，请检查文件路径是否正确。")
except Exception as e:
    print(f"发生未知错误: {e}")